package com.zhm.demo.util;

import com.zhm.demo.pojo.DeviceSummaryData;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.HashMap;
import java.util.Map;

public class ElScriptUtils {

    public static Object evalVal(String language, Map<String, Object> param, String eval) {

        // 表达式解析器
        ExpressionParser parser = new SpelExpressionParser();
        // 表达式上下文
        EvaluationContext context = new StandardEvaluationContext();
        param.forEach((k,v)->{
            context.setVariable(k, v);
        });

        // 解析
        Expression expression = parser.parseExpression(eval, new TemplateParserContext());
        return expression.getValue(context, String.class);

    }

    public static void main(String[] args) {
        Map<String, Object> param = new HashMap<>();
        DeviceSummaryData deviceSummaryData = new DeviceSummaryData();
        deviceSummaryData.setAcInputCurrent(2);

        param.put("c", deviceSummaryData);
        param.put("a", "123");
        param.put("b", "456");
        Object o = evalVal("el", param, "#{ 2!=2 ? 'Hello' : #c.acInputCurrent }");
        System.out.println(o);
    }


}
